from django.contrib.auth.mixins import LoginRequiredMixin
from django import http


class LoginRequiredJSONMixin(LoginRequiredMixin):
    """自定义判断用户是否登录的扩展类，返回JSON"""
    def handle_no_permission(self):
        """直接响应JSON数据"""
        # 只需要重写父类的 handle_no_permission方法，因为判断用户是否登录的操作，父类已经完成
        # 自雷只需要关心如果未登录成功的返回值就行
        return http.JsonResponse({
            'code': '4010',
            'errmsg': '用户未登录'
            }
        )
"""
    def handle_no_permission(self):
        if self.raise_exception or self.request.user.is_authenticated:
            raise PermissionDenied(self.get_permission_denied_message())
        return redirect_to_login(self.request.get_full_path(), self.get_login_url(), self.get_redirect_field_name())


class LoginRequiredMixin(AccessMixin):
    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_authenticated:
            return self.handle_no_permission()
        return super().dispatch(request, *args, **kwargs)
"""
